package com.cryptooj.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cryptooj.project.common.ErrorCode;
import com.cryptooj.project.constant.CommonConstant;
import com.cryptooj.project.exception.BusinessException;
import com.cryptooj.project.exception.ThrowUtils;
import com.cryptooj.project.model.vo.QuestionPartialVO;
import com.cryptooj.project.utils.SqlUtils;
import com.cryptooj.project.mapper.QuestionMapper;
import com.cryptooj.project.model.dto.question.QuestionQueryRequest;
import com.cryptooj.project.model.entity.User;
import com.cryptooj.project.model.entity.Question;
import com.cryptooj.project.model.vo.QuestionVO;
import com.cryptooj.project.model.vo.UserVO;
import com.cryptooj.project.service.QuestionService;
import com.cryptooj.project.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *  题目service的实现类
 * */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Resource
    private UserService userService;

    /**
     *  校验题目是否合法
     * */
    @Override
    public void validQuestion(Question question, boolean add) {
        if(question == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = question.getTitle();
        String content = question.getContent();
        String answer = question.getAnswer();
        String tags = question.getTags();
        String judgeCase = question.getJudgeCase();
        String judgeConfig = question.getJudgeConfig();
        if(add){
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title,content,tags),ErrorCode.PARAMS_ERROR);
        }
        if(StringUtils.isNotBlank(title) && title.length() > 80){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"标题过长");
        }
        if(StringUtils.isNotBlank(content) && content.length() > 1024*8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"内容过长");
        }
        if(StringUtils.isNotBlank(answer) && answer.length() > 1024*8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"答案过长");
        }
        if(StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 1024*8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"判题用例过长");
        }
        if(StringUtils.isNotBlank(judgeConfig) && judgeConfig.length() > 1024*8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"判题配置过长");
        }
    }

    /**
     *  获取题目查询条件，收集成QueryWrapper
     * */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if(questionQueryRequest == null){
            return queryWrapper;
        }
        Long id = questionQueryRequest.getId();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        String answer = questionQueryRequest.getAnswer();
        List<String> tags = questionQueryRequest.getTags();
        Long userId = questionQueryRequest.getUserId();

        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(title),"title",title);
        queryWrapper.like(StringUtils.isNotBlank(content),"content",content);
        queryWrapper.like(StringUtils.isNotBlank(answer),"answer",answer);
        if(CollectionUtils.isNotEmpty(tags)){
            for(String tag : tags){
                queryWrapper.like("tags","\""+tag+ "\""); // tags  \tag1\ \tag2\
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id),"id",id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId),"userId",userId);
        queryWrapper.eq("isDelete",false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    /**
     *  获取QuestionVO（将 mapper 返回的 Question 转化为 QuestionVO ）
     * */
    @Override
    public QuestionVO getQuestionVO(Question question, HttpServletRequest request) {
        QuestionVO questionVO = QuestionVO.objToVo(question);
        Long questionId = question.getId();
        // 获取题目的创建人
        User user = null;
        Long userId = question.getUserId();
        if(userId != null && userId > 0){
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionVO.setUserVO(userVO);
        return questionVO;
    }

    /**
     *  获取QuestionPartialVO（将 mapper 返回的 Question 转化为 QuestionPartialVO ）
     * */
    @Override
    public QuestionPartialVO getQuestionPartialVO(Question question, HttpServletRequest request) {
        QuestionPartialVO questionPartialVO = QuestionPartialVO.objToVo(question);
        Long questionId = question.getId();
        // 获取题目的创建人
        User user = null;
        Long userId = question.getUserId();
        if(userId != null && userId > 0){
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionPartialVO.setUserVO(userVO);
        return questionPartialVO;
    }

    /**
     *  获取分页后的题目VO
     * */
    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(
                questionPage.getCurrent(),
                questionPage.getSize(),
                questionPage.getTotal());
        if(CollectionUtils.isEmpty(questionList)){
            return questionVOPage;
        }
        // 题目创建人 用户id 集合
        Set<Long> userIdSet = questionList
                .stream()
                .map(Question::getUserId)
                .collect(Collectors.toSet());
        // 这里的写法能用，但是不直观
        // 实际效果：构造userId - User对
        Map<Long, List<User>> userIdUserListMap = userService
                .listByIds(userIdSet) // 根据创建人 用户id 获取创建人的 用户对象 ，得到用户列表List<User>
                .stream()
                .collect(Collectors.groupingBy(User::getId)); // 类似sql聚合函数效果： userId -- user1 user2 user3...，但是实际上这里的groupingBy聚合效果为一个userID对应一个user对象(存在更好写法）
        List<QuestionVO> questionVOList = questionList
                .stream()
                .map(question -> {
                    QuestionVO questionVO = QuestionVO.objToVo(question);
                    Long userId = question.getUserId();
                    User user = null;
                    if(userIdUserListMap.containsKey(userId)){
                        user = userIdUserListMap.get(userId).get(0);
                    }
                    UserVO userVO = userService.getUserVO(user);
                    questionVO.setUserVO(userVO);
                    return questionVO;
                })
                .collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }
}
